import React, { Fragment } from 'react'
import { View, StyleSheet, Text, FlatList } from 'react-native'
import { connect } from 'react-redux'
import BasePage from 'src/pageP/base/base-page/index'
import { UPDATEUSERINFOACTION } from 'src/store/actions/userinfo'
import CustomButton from 'src/components/button/CustomButton'
import {
  ScaleS,
  ScaleT,
  ONE_PIXEL,
  NAVIGATIONBAR_HEIGHT
} from 'src/utils/ScreenUtil'
import CheckDeleteView from 'src/components/check-delete-view/index'
import CustomImage from 'src/components/image/CustomImage'
import { openCamera, multipleAlums } from 'src/utils/ImagePickerUtil'
import { isArrayFn } from 'src/utils/JSTypeUtil'
import CustomStatusBar from 'src/components/header/CustomStatusBar'
import { delImg, insertImg } from 'src/utils/RequestAPI'
import { CommonToast, DismissLoading, ShowLoading } from 'src/utils/ToastUtil'
import { showImageViewerModal, showTipModal, showSelectModal } from 'src/utils/ModalUtil'
import { ImageHost } from 'src/config/index'
import { UPDATE_USER_ARCHIVE_IMG_ACTION } from '../../mine/mine-page/store/action'
import { uploadImgs } from 'src/utils/ImageUploadUtil'

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATEUSERINFOACTION(payload))
  },
  updateUserArchiveImg (payload) {
    dispatch(UPDATE_USER_ARCHIVE_IMG_ACTION(payload))
  }

})

@connect(({ CMineCenterStore, userinfo }) => ({
  userArchiveImgModels: CMineCenterStore.userArchiveImgModels,
  userinfoC: userinfo.C
}), mapDispatchToProps)
class CMyPhotoAlbums extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      titleText: '',
      tipPromptVisible: false,
      checkedIds: [],
      selectAll: false,
      isManager: true,
      selectModalVisible: false,
      showImageViewer: false,
      dataArr: this._transformDataArr(),
      initIndex: 0
    }
    this.selectModalConfig = {
      selectArr: [
        {
          label: '相册上传'
        },
        {
          label: '拍照上传'
        }],
      titleText: '添加照片',
      onCancel: this._selectModalCancel,
      selectClick: this._selectModalClick
    }
    this.config = {
      titleLabel: '提醒',
      contentText: '确定要删除所选照片吗？',
      onCancel: this.onTipCancel,
      onConfirm: this.onTipConfirm
    }
    this.currentConfig = {
      titleLabel: '提醒',
      contentText: '确定要删除所选照片吗？',
      onCancel: this.onCurrentTipCancel,
      onConfirm: this.onCurrentTipConfirm
    }
  }

  _transformDataArr = () => {
    const { userArchiveImgModels } = this.props
    return userArchiveImgModels.map((item) => {
      item.url = ImageHost + item.imgUrl
      return item
    })
  }

  _selectModalClick = index => {
    switch (index) {
      case 0:
        this.selectModal.close(() => {
          multipleAlums().then((images) => {
            this._addImage(images)
          })
        })
        break
      case 1:
        this.selectModal.close(() => {
          openCamera({
            width: 750, height: 750
          }).then((image) => {
            console.info(image)
            this._addImage(image)
          })
        })
        break
      default:
        this.selectModal.close()
    }
  }

  _addImage = (img) => {
    if (isArrayFn(img)) {
      this._uploadImages(img)
    } else {
      this._uploadImages([img])
    }
  }

  _uploadImages = (images) => {
    ShowLoading()
    uploadImgs({ localImgs: images }).then((result) => {
      if (result.length > 0) {
        this._uploadImage(result)
      } else {
        CommonToast('图片上传失败')
        DismissLoading()
      }
    })
  }

  _uploadImage = (userArchiveImgModels = []) => {
    const { userinfoC, updateUserArchiveImg } = this.props
    insertImg({
      params: {
        userId: userinfoC.userId,
        imgUrls: userArchiveImgModels.join(',')
      }
    }).then((data) => {
      // CommonToast(`${userArchiveImgModels.length}张图片上传成功`)
      const newDataArr = data.data ? data.data.map((item) => {
        item.url = ImageHost + item.imgUrl
        return item
      }) : []
      this.setState({
        dataArr: newDataArr
      })
      updateUserArchiveImg({
        userArchiveImgModels: newDataArr
      })
      DismissLoading()
    }).catch((data) => {
      console.info(data)
      DismissLoading()
    })
  }

  _renderNavigation () {
    const { isManager, titleText } = this.state
    return (
      <Fragment>
        <CustomStatusBar/>
        <View style={styles.headerView}>
          <View style={styles.headerLeftView}>
            <CustomButton style={styles.headerLeftImgView} onPress={this._onHeaderLeft}>
              <CustomImage
                style={styles.headerLeftImg}
                source={isManager ? require('@/imgC/home/btnBack.png') : require('@/imgC/userinfo/close_black2.png')}/>
            </CustomButton>
          </View>
          <View style={styles.headerCenterView}>
            <Text style={styles.headerCenterText}>{titleText}</Text>
          </View>
          <View style={styles.headerRightView}>
            {
              isManager ? (
                <CustomButton style={styles.managerView} onPress={this._changeManager}>
                  <Text style={styles.managerText}>{'管理'}</Text>
                </CustomButton>
              ) : null
            }
          </View>
        </View>
      </Fragment>
    )
  }

  _onHeaderLeft = () => {
    const { isManager } = this.state
    const { navigation } = this.props
    if (isManager) {
      navigation.goBack()
    } else {
      this._closeManager()
    }
  }

  _closeManager = () => {
    const { isManager } = this.state
    this.setState({
      isManager: !isManager,
      titleText: '',
      checkedIds: [],
      selectAll: false
    })
  }

  _changeManager = () => {
    const { isManager, dataArr } = this.state
    this.setState({
      isManager: !isManager,
      dataArr: [...dataArr],
      titleText: '管理照片'
    })
  }

  childRender () {
    const {
      selectAll, dataArr, isManager, checkedIds
    } = this.state
    return (
      <View style={styles.container}>
        {this._renderNavigation()}
        <Text style={styles.titleText}>我的相册</Text>
        {
          isManager ? (
            <CustomButton style={styles.uploadImgView} onPress={this._uploadImgClick}>
              <CustomImage style={styles.uploadImg} source={require('@/imgC/userinfo/add_black.png')}/>
              <Text style={styles.uploadText}>上传照片</Text>
            </CustomButton>
          ) : null
        }
        <FlatList
          style={styles.flatList}
          extraData={checkedIds}
          data={dataArr}
          horizontal={false}
          numColumns={3}
          renderItem={this._renderItem}
          keyExtractor={this._keyExtractor}/>
        {
          isManager ? null : (
            <Fragment>
              <View style={styles.line}/>
              <CheckDeleteView
                checked={selectAll}
                highlight={checkedIds.length > 0}
                onCheckedPress={this.selectAll}
                onDeletePress={this.onDelete}/>
            </Fragment>
          )
        }
      </View>
    )
  }

  _uploadImgClick = () => {
    this._toggleSelectModal(true)
  }

  _toggleSelectModal = (selectModalShow, callBack) => {
    if (selectModalShow) {
      this.selectModal = showSelectModal(this.selectModalConfig)
    } else {
      if (this.selectModal) {
        this.selectModal.close(() => {
          callBack && callBack()
        })
      }
    }
  }

  _selectModalCancel = () => {
    this._toggleSelectModal(false)
  }

  _deleteCurrentImg = (currentIndex) => {
    this.currentIndex = currentIndex
    this._toggleCurrentTipModal(true)
  }

  onCurrentTipCancel = () => {
    this._toggleCurrentTipModal(false)
  }

  // 删除确认提示
  onCurrentTipConfirm = () => {
    const { dataArr } = this.state
    const { userinfoC, updateUserArchiveImg } = this.props
    this._toggleCurrentTipModal(false, () => {
      delImg({
        params: {
          userId: userinfoC.userId,
          ids: dataArr[this.currentIndex].id.toString()
        }
      }).then(() => {
        CommonToast('照片删除成功')
        const remainDatas = dataArr.filter((item, index) => {
          return this.currentIndex !== index
        })

        if (remainDatas.length > 0) {
          this.setState({
            dataArr: remainDatas,
            initIndex: this.currentIndex - 1 > 0 ? this.currentIndex - 1 : 0
          }, () => {
            console.info('updateModal_renderImageViewer')
            this.imgageViewerModal.update(this._renderImageViewer())
          })
        } else {
          this.imgageViewerModal.close()
          this.setState({
            dataArr: remainDatas
          })
        }
        updateUserArchiveImg({
          userArchiveImgModels: remainDatas
        })
      })
    })
  }

  _toggleCurrentTipModal = (currentTipModalShow, callBack) => {
    if (currentTipModalShow) {
      this.currentTipModal = showTipModal(this.currentConfig)
    } else {
      if (this.currentTipModal) {
        this.currentTipModal.close(() => {
          callBack && callBack()
        })
      }
    }
  }

  _keyExtractor = item => item.id

  _renderItem = ({ item, index }) => {
    const { checkedIds } = this.state
    return (
      <CustomButton style={styles.itemView} onPress={this._imgItemClick} params={{ item, index }}>
        <CustomImage style={styles.itemImg} source={{ uri: item.url }}/>
        {
          checkedIds.includes(item.id) ? (
            <View style={styles.itemCloseView}>
              <CustomImage style={styles.itemCloseImg} source={require('@/imgC/userinfo/icon_white_ok.png')}/>
            </View>
          ) : null
        }
      </CustomButton>
    )
  }

  _imgItemClick = ({ item, index }) => {
    const { isManager, checkedIds, dataArr } = this.state
    if (isManager) {
      this.setState({
        initIndex: index
      }, () => {
        this._showImageViewer()
      })
    } else {
      let newCheckedIds
      if (checkedIds.includes(item.id)) {
        newCheckedIds = checkedIds.filter(checkId => item.id !== checkId)
      } else {
        newCheckedIds = checkedIds.concat(item.id)
      }
      let titleText
      if (newCheckedIds.length > 0) {
        titleText = '已选' + newCheckedIds.length + '张照片'
      } else {
        titleText = '管理照片'
      }
      this.setState({
        selectAll: newCheckedIds.length >= dataArr.length,
        checkedIds: newCheckedIds,
        titleText
      })
    }
  }

  _showImageViewer = () => {
    const { dataArr, initIndex } = this.state
    this.imgageViewerModal = showImageViewerModal({
      onClose: this._closeImageViewerModal,
      images: dataArr,
      initIndex
    })
  }

  _closeImageViewerModal = () => {
    if (this.imgageViewerModal) {
      this.imgageViewerModal.close()
    }
  }

  selectAll = ({ checked }) => {
    const { dataArr } = this.state
    let newCheckedIds
    let titleText
    if (checked) {
      newCheckedIds = []
      titleText = '管理照片'
    } else {
      newCheckedIds = dataArr.map((item, index) => item.id)
      titleText = '已选' + newCheckedIds.length + '张照片'
    }
    this.setState({
      selectAll: !checked,
      checkedIds: newCheckedIds,
      titleText
    })
  }

  onDelete = () => {
    const { checkedIds } = this.state
    if (checkedIds.length > 0) {
      this._toggleTipModal(true)
    }
  }

  onTipCancel = () => {
    this._toggleTipModal(false)
  }

  // 删除确认提示
  onTipConfirm = () => {
    const { checkedIds, dataArr } = this.state
    const { userinfoC, updateUserArchiveImg } = this.props
    this._toggleTipModal(false, () => {
      delImg({
        params: {
          userId: userinfoC.userId,
          ids: checkedIds.join(',')
        }
      }).then(() => {
        CommonToast('照片删除成功')
        const remainDatas = dataArr.reduce((newDataArr, currentValue) => {
          return checkedIds.includes(currentValue.id) ? newDataArr : newDataArr.concat(currentValue)
        }, [])
        this.setState({
          checkedIds: [],
          titleText: '管理照片',
          dataArr: remainDatas
        })
        // ToDo
        this._closeManager()
        updateUserArchiveImg({
          userArchiveImgModels: remainDatas
        })
      })
    })
  }

  _toggleTipModal = (tipModalShow, callBack) => {
    if (tipModalShow) {
      this.tipModal = showTipModal(this.config)
    } else {
      if (this.tipModal) {
        this.tipModal.close(() => {
          callBack && callBack()
        })
      }
    }
  }
}

export default CMyPhotoAlbums

const
  styles = StyleSheet.create({
    container: {
      flex: 1
    },
    headerView: {
      height: ScaleS(44),
      flexDirection: 'row',
      alignItems: 'center'
    },
    headerLeftView: {
      flex: 1
    },
    headerLeftImg: {
      width: ScaleS(19),
      height: ScaleS(13)
    },
    headerLeftImgView: {
      paddingHorizontal: ScaleS(20)
    },
    headerCenterView: {
      flex: 2,
      alignItems: 'center'
    },
    headerCenterText: {
      color: '#030303',
      fontSize: ScaleT(17),
      fontWeight: '400'
    },
    headerRightView: {
      flex: 1,
      alignItems: 'flex-end',
      paddingRight: ScaleS(20)
    },
    managerView: {
      width: ScaleS(58),
      height: ScaleS(28),
      borderRadius: ScaleS(14),
      alignItems: 'center',
      justifyContent: 'center',
      borderColor: '#000000',
      borderWidth: ScaleS(1),
      borderStyle: 'solid'
    },
    managerText: {
      color: '#000000',
      fontSize: ScaleT(12),
      fontWeight: '600'
    },
    uploadImgView: {
      height: ScaleS(47),
      alignItems: 'center',
      flexDirection: 'row',
      paddingHorizontal: ScaleS(20),
      backgroundColor: '#F7F7F7',
      borderRadius: ScaleS(5),
      marginHorizontal: ScaleS(20),
      marginBottom: ScaleS(26)
    },
    uploadImg: {
      width: ScaleS(14),
      height: ScaleS(14)
    },
    uploadText: {
      color: '#000000',
      fontSize: ScaleT(14),
      fontWeight: '400',
      marginLeft: ScaleS(9)
    },
    line: {
      height: ONE_PIXEL,
      backgroundColor: '#EFEFEF'
    },
    titleText: {
      color: '#444444',
      fontSize: ScaleT(25),
      fontWeight: '600',
      marginTop: ScaleS(30),
      marginLeft: ScaleS(20),
      marginBottom: ScaleS(30)
    },
    imageViewerHeaderView: {
      height: NAVIGATIONBAR_HEIGHT,
      backgroundColor: 'white'
    },
    imageViewerHeader: {
      position: 'absolute',
      bottom: 0,
      left: 0,
      right: 0,
      height: ScaleS(44),
      alignItems: 'center',
      flexDirection: 'row'
    },
    imageViewerLeftView: {
      flex: 1,
      alignItems: 'flex-start'
    },
    imageViewerLeftImgView: {
      paddingHorizontal: ScaleS(24),
      height: ScaleS(44),
      alignItems: 'center',
      justifyContent: 'center'
    },
    imageViewerLeftImg: {
      width: ScaleS(15),
      height: ScaleS(15)
    },
    imageViewerCenterView: {
      flex: 1,
      alignItems: 'center'
    },
    imageViewerCenter: {
      color: '#000000',
      fontSize: ScaleT(16),
      fontWeight: '400'
    },
    imageViewerRightView: {
      flex: 1,
      alignItems: 'flex-end'
    },
    imageViewerRightTextView: {
      paddingHorizontal: ScaleS(24),
      height: ScaleS(44)
    },
    imageViewerRightText: {
      color: '#030303',
      fontSize: ScaleT(17),
      fontWeight: '400',
      lineHeight: ScaleS(44)
    },
    flatList: {
      flex: 1,
      marginHorizontal: ScaleS(20)
    },
    itemView: {
      width: ScaleS(112),
      height: ScaleS(112),
      alignItems: 'center'
    },
    itemImg: {
      width: ScaleS(111),
      height: ScaleS(111),
      resizeMode: 'cover',
      borderRadius: ScaleS(4)
    },
    itemCloseView: {
      width: ScaleS(20),
      height: ScaleS(20),
      backgroundColor: '#000000',
      borderRadius: ScaleS(10),
      justifyContent: 'center',
      alignItems: 'center',
      position: 'absolute',
      top: ScaleS(6),
      right: ScaleS(6)
    },
    itemCloseImg: {
      width: ScaleS(12),
      height: ScaleS(8)
    }
  })
